<template>
  <div class="app-container">
    <el-form ref="formRef" :disabled="id" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="预测数据">
        <el-upload
          ref="upload"
          :before-remove="beforeRemove"
          :file-list="fileList"
          :http-request="uploadHttpRequest"
          :limit="1"
          :on-change="uploadFiles"
          :on-exceed="handleExceed"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          action="#"
          class="upload-demo"
          multiple
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只支持csv/mat格式文件</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="RUL" prop="rul">
        <el-input
          v-model="form.rul"
          disabled
        />
      </el-form-item>

      <el-form-item label="模型" prop="model">
        <el-select v-model="form.model" placeholder="请选择模型">
          <el-option
            v-for="item in modelList"
            :key="item.mid"
            :label="item.name"
            :value="item.mid"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="元器件" prop="componentsPart">
        <el-select v-model="form.componentsPart" placeholder="请选择元器件">
          <el-option
            v-for="item in componentsParts"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工况" prop="workingCondition">
        <el-select v-model="form.workingCondition" placeholder="请选择工况">
          <el-option
            v-for="item in gkParts"
            :key="item.conditionId"
            :label="item.conditionId"
            :value="item.conditionId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="操作">
        <el-button v-if="!id" type="primary" @click="forecast">预测</el-button>
        <el-button @click="$router.back()">取消</el-button>
        <el-button v-if="forecastResult && forecastResult.length" type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
    <el-card>
      <div slot="header"><span>元器件剩余寿命预测曲线</span></div>
      <div class="el-table el-table--enable-row-hover el-table--medium">
        <div ref="resEchart" style="height: 420px"/>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { Download, Predict } from '../../../api/bearing/predict'
import { listMangment } from '@/api/bearing/mangment'
import { upload } from '@/api/common'
import { addResult, getResult ,getyqjList,getgkList} from '@/api/bearing/result'

export default {
  name: 'Predict',
  data() {
    return {
      id: undefined,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      fileList: [],
      componentsParts: [],
      signalAnalysisType1: true,
      loadingParts: false, 
      signalAnalysisType2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        filtering: null,
        name: null,
        datasetName: null,
        conditionName: null,
        bearingName: null
      },
      // 表单参数
      form: {
        // 结果文件url
        resultFileUrl: undefined,
        // 预测文件url
        forecastFileUrl: undefined,
        // 曲线
        curve: undefined,
        componentsPart: undefined,
        model: undefined,
        rul: undefined,
        modelName: undefined,
        componentsPartName: undefined,
        workingCondition: undefined
      },
      predictResultData: [],
      rul: null,
      resEchart: null,
      // 表单校验
      rules: {
        model: [
          { required: true, message: '请选择模型', trigger: 'blur' }
        ],
        componentsPart: [
          { required: true, message: '请选择元器件', trigger: 'blur' }
        ]
      },
      forecastResult: null,
      modelList: [],
      
    }
  }
  ,
  /**
   * 数据发生改变
   */

  watch: {}
  ,

  /**
   * 创建完毕
   */

  created() {
    this.getModelList();
    this.getyqjList();
    const id = this.$route.query?.id
    this.getgkList();
    this.id = id
    
    if (id) {
      this.findInfo()
    }
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    async getgkList() {
      const res = await getgkList()
      
      this.gkParts = res
    },
    async getyqjList() {
      const res = await getyqjList()
    
      this.componentsParts = res
    },

    async findInfo() {
      const res = await getResult(this.id)
      this.form = res.data

      if (this.form.curve) {
        this.drawCurve(JSON.parse(this.form.curve))

      }
    },
    async handleSave() {
      await this.$refs.formRef.validate()

      if (!this.form.rul) {
        this.$modal.msgError('请先预测')
        return
      }

      // 保存数据
      await addResult(this.form)
      this.$modal.msgSuccess('保存成功')

      // 跳转列表
      this.$router.push({ path: '/predict/result' })

    },
    async getModelList() {
      const result = await listMangment({})
      this.modelList = result.rows
    },
    // 查询所有元器件信息
    async forecast() {
      let formData = new FormData()
      if ('undefined' === typeof (this.form.files)) {
        this.$modal.msgError('请上传数据文件')
        return
      }

      await this.$refs.formRef?.validate()

      // 上传源文件
      this.uploadForecastFile()

      formData.append('files', this.form.files[0].raw)

      const model = this.modelList.find(item => item.mid === this.form.model)

      if (model) {
        this.form.modelName = model.name
        this.form.modelType = model.type
      }

      this.form.componentsPartName = this.componentsParts.find(item => item.typeId === this.form.componentsPart)?.typeName

      formData.append('rulModel', this.form.modelName)
      formData.append('rulType', this.form.componentsPartName)
      // 将其他数据写入json对象
      this.loading = true
      Predict(formData)
        .then(response => {
          let rul = response.data.rul
          let curve = response.data.curve
          this.forecastResult = curve
          this.form.curve = JSON.stringify(curve)

          this.form.rul = curve[1][curve[1].length - 1]

          this.drawCurve(curve)

          this.loading = false
          // 下载上传文件
          this.handleDownloadAndUploadFile()

        }).catch(() => {
        this.loading = false
      })
    },
    drawCurve(curve) {
      this.resEchart = echarts.init(this.$refs.resEchart, 'macarons')

      this.resEchart.on('click', (params) => {
        if (params.seriesName !== 'RUL') {
          return
        }

        this.form.rul = params.value
      });


      const midIndex = Math.floor(curve[0].length / 2)

      this.resEchart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: curve[0]
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: 'RUL',
            type: 'line',
            data: curve[1].map((value, index) => ({
              value: value,
              itemStyle: {
                color: index < midIndex ? 'red' : 'green'
              }
            }))
          }
        ]
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    uploadHttpRequest(data) {
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    uploadFiles(item, fileList) {
      this.form.files = fileList
    },
    async uploadForecastFile() {
      const formData = new FormData()
      formData.append('file', this.form.files[0].raw)

      const res = await upload(formData)
      this.form.forecastFileUrl = res.url
    },
    async handleDownloadAndUploadFile() {
      const res = await Download()
      const blob = new Blob([res], { type: 'application/csv' })
      // 上传文件
      const file = new File([blob], 'result.csv', { type: 'application/csv' })

      const formData = new FormData()
      formData.append('file', file)

      const uploadRes = await upload(formData)
      this.form.resultFileUrl = uploadRes.url
    },
    handleDownload() {
      Download().then(res => {
        const blob = new Blob([res], { type: 'application/csv' })
        const url = URL.createObjectURL(blob)
        let anchor = document.createElement('a')
        //设置下载的文件名
        anchor.download = `result_${new Date().getTime()}.csv`
        anchor.href = url
        anchor.click()
      })
    }
  }
}
</script>
